# coding:utf-8

from flask import request, current_app, render_template, redirect, url_for, flash
from flask_login import login_required

from ..extensions import db
from . import op_bp
from .models import PricePackSet
from .pack_forms import PricePackSetForm


@op_bp.route('/price_pack_set_list')
@login_required
def price_pack_set_list():
    """
    充值套餐列表
    """

    query = PricePackSet.query
    page = request.args.get('page', 1, type=int)
    pagination = query.order_by(
        PricePackSet.id
    ).paginate(
        page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    items = pagination.items
    return render_template(
        'pack/price_pack_set_list.html',
        page=page,
        items=items,
        pagination=pagination,
    )


@op_bp.route('/price_pack_set_add', methods=['GET', 'POST'])
@login_required
def price_pack_set_add():
    """
    新增充值套餐
    """
    form = PricePackSetForm()

    if form.validate_on_submit():
        if PricePackSet.query.filter(
                PricePackSet.name == form.name.data
            ).first():
            flash('套餐名重复,请注意检查')
            return redirect(url_for('op_bp.price_pack_set_add', ))

        new_price_pack_set = PricePackSet()
        form.populate_obj(new_price_pack_set)
        db.session.add(new_price_pack_set)
        db.session.flush()

        flash('新增成功')
        return redirect(url_for('op_bp.price_pack_set_list'))
    else:
        if form.errors:
            flash('表单数据有误，请检查')
            print(form.errors)

    return render_template(
        'pack/price_pack_set_add.html',
        form=form,
    )


@op_bp.route('/price_pack_set_edit/<int:pack_id>', methods=['GET', 'POST'])
@login_required
def price_pack_set_edit(pack_id):
    """
    编辑充值套餐
    """
    form = PricePackSetForm()

    price_pack_set = PricePackSet.query.get_or_404(pack_id)
    if form.validate_on_submit():
        if PricePackSet.query.filter(
                PricePackSet.id != pack_id,
                PricePackSet.name == form.name.data
            ).first():
            flash('套餐名重复,请注意检查')
            return redirect(
                url_for('op_bp.price_pack_set_edit', pack_id=pack_id)
            )

        form.populate_obj(price_pack_set)
        flash('修改成功')
        return redirect(url_for('op_bp.price_pack_set_list'))

    form = PricePackSetForm(obj=price_pack_set)
    return render_template(
        '/pack/price_pack_set_edit.html',
        price_pack_set=price_pack_set,
        form=form
    )
